<template>
  <div>
    <a-button @click="openAdd">添加</a-button>
    <a-table
      :columns="columns"
      :row-selection="rowSelection"
      :rowKey="`userId`"
      :data-source="userPage.records"
      :pagination="false"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'userId'">
          <a-button type="primary" @click="openEdit(record)">修改</a-button>
          <a-popconfirm
            @confirm="sureDeleted(record.menuId)"
            title="是否要删除该节点"
          >
            <a-button type="primary" danger> 删除</a-button>
          </a-popconfirm>
        </template>
      </template>
    </a-table>
    <a-modal
      v-model:visible="editVisible"
      title="修改"
      :footer="null"
      :maskClosable="false"
      :afterClose="resetForm"
    >
      <a-form
        ref="editFormRef"
        :model="userForm"
        name="basic"
        :label-col="{ span: 8 }"
        :wrapper-col="{ span: 16 }"
        autocomplete="off"
      >
        <a-form-item
          label="用户名称"
          name="username"
          :rules="[{ required: true, message: '用户名称不能为空' }]"
        >
          <a-input v-model:value="userForm.username" />
        </a-form-item>

        <a-form-item
          label="所属部门"
          name="deptId"
          :rules="[{ required: true, message: '所属部门不能为空' }]"
        >
          <a-tree-select
            v-model:value="userForm.deptId"
            :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
            placeholder="Please select"
            :fieldNames="{
              children: 'children',
              key: 'deptId',
              label: 'deptName',
              value: 'deptId',
            }"
            allow-clear
            tree-default-expand-all
            :tree-data="deptList"
          />
        </a-form-item>

        <a-form-item label="拥有的角色" name="roleIds">
          <a-select
            v-model:value="userForm.roleIds"
            :options="rolePage.records"
            mode="multiple"
            :fieldNames="{
              label: 'roleName',
              value: 'roleId',
            }"
          >
            <template #dropdownRender="{ menuNode: menu }">
              <v-nodes :vnodes="menu" />
              <a-divider style="margin: 4px 0" />
              <div
                style="padding: 4px 8px; cursor: pointer"
                @mousedown="(e) => e.preventDefault()"
              >
                <a-pagination
                  hideOnSinglePage
                  size="small"
                  v-model:current="rolePage.current"
                  :total="rolePage.total"
                  show-less-items
                  @change="changeRolePage"
                />
              </div>
            </template>
          </a-select>
        </a-form-item>

        <a-form-item label="启用状态" name="status">
          <a-switch
            v-model:checked="userForm.status"
            :checkedValue="1"
            :unCheckedValue="0"
          />
        </a-form-item>
        <a-form-item :wrapper-col="{ offset: 8, span: 16 }">
          <a-button type="primary" @click="edit" html-type="submit"
            >确定
          </a-button>
        </a-form-item>
      </a-form>
    </a-modal>

    <a-modal
      v-model:visible="addVisible"
      title="新增"
      :footer="null"
      :maskClosable="false"
      :afterClose="resetForm"
    >
      <a-form
        ref="addFormRef"
        :model="userForm"
        name="basic"
        :label-col="{ span: 8 }"
        :wrapper-col="{ span: 16 }"
        autocomplete="off"
      >
        <a-form-item
          label="用户名称"
          name="username"
          :rules="[{ required: true, message: '用户名称不能为空' }]"
        >
          <a-input v-model:value="userForm.username" />
        </a-form-item>

        <a-form-item
          label="所属部门"
          name="deptId"
          :rules="[{ required: true, message: '所属部门不能为空' }]"
        >
          <a-tree-select
            v-model:value="userForm.deptId"
            :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
            placeholder="Please select"
            :fieldNames="{
              children: 'children',
              key: 'deptId',
              label: 'deptName',
              value: 'deptId',
            }"
            allow-clear
            tree-default-expand-all
            :tree-data="deptList"
          />
        </a-form-item>
        <a-form-item label="启用状态" name="status">
          <a-switch
            v-model:checked="userForm.status"
            :checkedValue="1"
            :unCheckedValue="0"
          />
        </a-form-item>
        <a-form-item :wrapper-col="{ offset: 8, span: 16 }">
          <a-button type="primary" @click="add" html-type="submit"
            >确定
          </a-button>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import type { DeptVo, MenuVo, RoleVo, SysUserDto, SysUserVo } from "@/api";
import { Client } from "@/api/clientApi";
import { message } from "ant-design-vue";
import "ant-design-vue/es/message/style/css";
import { onMounted, reactive, ref } from "vue";

const VNodes = (_: any, { attrs }: any) => {
  return attrs.vnodes;
};

const columns = [
  {
    title: "用户id",
    dataIndex: "userId",
  },
  {
    title: "用户名",
    dataIndex: "username",
  },
  {
    title: "所在部门",
    dataIndex: ["sysDeptVo", "deptName"],
  },
  {
    title: "邮箱",
    dataIndex: "email",
  },
  {
    title: "手机号",
    dataIndex: "mobile",
  },
  {
    title: "启用状态",
    dataIndex: "status",
  },
  {
    title: "创建时间",
    dataIndex: "createTime",
  },
  {
    title: "创建时间",
    key: "userId",
  },
];

const userForm = reactive<SysUserDto>({
  userId: 0,
  username: "",
  deptId: null,
  mobile: "",
  status: 0,
  shopId: 0,
  roleIds: [],
});
const editFormRef = ref();
const addFormRef = ref();
/**
 * 修改弹窗的显示变量
 */
const editVisible = ref<boolean>(false);
/**
 * 打开修改弹窗
 * @param record
 */
const openEdit = async (record: SysUserVo) => {
  editVisible.value = true;
  const rest = await Client.systemSysUser.getSysUser(record.userId);
  userForm.userId = rest.userId;
  userForm.username = rest.username;
  userForm.deptId = rest.sysDeptVo.deptId;
  userForm.email = rest.email;
  userForm.mobile = rest.mobile;
  userForm.status = rest.status;
  userForm.shopId = rest.shopId;
  userForm.roleIds = rest.roleIds;
  await getRoleList();
};
/**
 * 提交更新
 */
const edit = () => {
  Client.systemSysUser.putSysUser(userForm).then(() => {
    editVisible.value = false;
    getUserList();

    message.success("修改成功");
  });
};

const addVisible = ref<boolean>(false);
const openAdd = () => {
  addVisible.value = true;
  getRoleList();
};
const add = () => {
  Client.systemSysUser.postSysUser(userForm).then(() => {
    addVisible.value = false;
    getUserList();
    message.success("添加成功");
  });
};

const sureDeleted = (id: number) => {
  Client.systemSysUser.deleteSysUser(id).then(() => {
    message.success("删除成功");
    getUserList();
  });
};

const rowSelection = ref({
  checkStrictly: false,
  onChange: (selectedRowKeys: (string | number)[], selectedRows: MenuVo[]) => {
    console.log(
      `selectedRowKeys: ${selectedRowKeys}`,
      "selectedRows: ",
      selectedRows
    );
  },
  onSelect: (record: MenuVo, selected: boolean, selectedRows: MenuVo[]) => {
    console.log(record, selected, selectedRows);
  },
  onSelectAll: (
    selected: boolean,
    selectedRows: MenuVo[],
    changeRows: MenuVo[]
  ) => {
    console.log(selected, selectedRows, changeRows);
  },
});

type UserPage = {
  records: SysUserVo[];
  size: number;
  current: number;
};
const userPage = reactive<UserPage>({
  records: [],
  size: 10,
  current: 1,
});

/**
 * 用户分页查询
 */
const getUserList = async () => {
  const { records, size, current } = await Client.systemSysUser.getSysUserPage(
    userPage.current,
    userPage.size
  );
  userPage.records = records;
  userPage.size = size;
  userPage.current = current;
};

/**
 * 查询 部门树
 */
const deptList = ref<DeptVo[]>([]);
const getDeptList = async () => {
  deptList.value = await Client.systemDept.getSysDeptDeptTree();
};

type RolePage = {
  records: RoleVo[];
  current: number;
  size: number;
  total: number;
};

const rolePage = reactive<RolePage>({
  records: [],
  current: 1,
  size: 10,
  total: 0,
});

/**
 * 分页查询角色列表
 */
const getRoleList = async () => {
  const { records, current, size, total } =
    await Client.systemRole.getSysRolePage(rolePage.current, rolePage.size);
  rolePage.records = records;
  rolePage.current = current;
  rolePage.size = size;
  rolePage.total = total;
};

const changeRolePage = (page: number, pageSize: number) => {};

/**
 * 重置表单对象
 */
const resetForm = () => {
  userForm.userId = 0;
  userForm.username = "";
  userForm.deptId = null;
  userForm.mobile = "";
  userForm.email = "";
  userForm.status = 0;
  userForm.shopId = 0;
  userForm.roleIds = [];

  // 重置角色数据,保证都是新数据
  rolePage.records = [];
  rolePage.size = 10;
  rolePage.current = 1;
  rolePage.total = 0;
};
onMounted(() => {
  getUserList();
  getDeptList();
  getRoleList();
});
</script>

<style scoped></style>
